#include <QCoreApplication>

#include <QDebug>

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <QThread>

#include "../memshare/memory_share.h"

#include <iostream>

using namespace cv;



int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    std::cout << "start---------------------" << std::endl;

//    cv::Mat src = cv::imread("E:\\TestImgs\\common\\t1.jpg");
//    Mat dst;
//    resize(src, dst, cv::Size(640, 480), 0, 0, cv::INTER_LINEAR);
//    imshow("dst", dst);
//    waitKey();




    VideoCapture cap(0);
    if(!cap.isOpened())
    {
        return -1;
    }
    Mat im;
    Mat dst;
    //Mat edges;

    bool stop = false;
    if (!cap.read(im))
    {
        qDebug() << "init failed";
        return -1;
    }
    dst = im;
    std::cout << "-----read first frame-------" << std::endl;

    int len = im.rows * im.cols * im.channels() * sizeof(char);
    char* p = (char*)malloc( len );
    qDebug() << "img len: " << len;

    MemoryShare memshare;//("demo_share");
    if ( !memshare.init())
    {
        std::cout << "------mem share init failed------" << std::endl;
       return 0;
    }

    std::cout << "-----mem share init success-------" << std::endl;
    while (!stop)
    {
        std::cout << "------------" << std::endl;
        if (!cap.read(im))
        {
            stop = true;
            continue;
        }
        // cap >> im;
        //cvtColor(frame, edges, CV_BGR2GRAY);


        memcpy(p, im.data, len);
        //memcpy(dst.data, p, im.rows * im.cols * im.channels() * sizeof(uchar));
        //imshow("Display Image", dst);



        qDebug() << "begin write";
//        std::string a = "aaaa";
//        len = a.size();
        if(!memshare.write(p, len))
        {
            qDebug() << "write failed";
        }
        else
        {
            qDebug() << "write success";
        }



        imshow("Display Image", im);

        //GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
        //Canny(edges, edges, 0, 30, 3);
        //imshow("video",frame);
        //imshow("video",edges);
        int key = waitKey(50) ;
        if(key != 255)
        {
            std::cout << key << std::endl;
            std::cout << "exit manually.."<< std::endl;
            stop = true;
        }
    }


    //getchar();
    qDebug() << "begin exit";
    memshare.exit();
    qDebug() << "exit done";


    free(p);
    return 0;
    //return a.exec();
}
